package servlets;

import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cmput391.src.queries.*;
import  src.entities.*;
import exceptions.*;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String username = (request.getParameter("username")).trim();
		String password = (request.getParameter("password")).trim();
		
		DBConnector dbConnect = new DBConnector();
		SecurityQueries security = null;
		LoginQueries login = null; 
		User user = null;
		try {
			security = new SecurityQueries(dbConnect.getConnection());
			login = new LoginQueries(dbConnect.getConnection(), security);
			user = login.verifyLogin(username, password);
			
			HttpSession session = request.getSession(true);
			session.setAttribute("authorized",true);
			session.setAttribute("userClass", user.getUserClass());		
			session.setAttribute("username", user.getUserName());
			session.setAttribute("password", user.getPassword());		
			session.setAttribute("firstrun", false);
			response.sendRedirect("UpdateProfile");				
		} catch (ClassNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (SQLException e1) {
			e1.printStackTrace();
		} catch (InstantiationException e1) {
			e1.printStackTrace();
		} catch (IllegalAccessException e1) {
			e1.printStackTrace();
		} catch (InvalidLoginException e1) {
			Map<String, String> messages = new HashMap<String, String>();
			request.setAttribute("messages", messages);
			messages.put("login_msg", "<span class=\"message warning\">Invalid Login. Please try again.</span>");
			request.getRequestDispatcher("index.jsp").include(request,response);			
		}
	}

}
